/**
 * 编辑宠物页面
 * 功能：修改宠物基本信息
 */

const app = getApp();
const apiService = require('../../../utils/api.js');

Page({
  data: {
    // 系统状态栏高度
    statusBarHeight: 44,
    
    // 导航栏滚动状态
    scrollY: 0,
    navbarOpacity: 0,  // 导航栏背景透明度 (0-1)
    navbarTextColor: '#FFFFFF', // 导航栏文字颜色
    
    // 宠物ID
    petId: '',
    
    // 表单数据
    formData: {
      nickname: '',
      category: '', // cat/dog
      breed: '',
      gender: '', // male/female
      birthDate: '',
      weight: '',
      avatar: ''
    },
    
    // 性别选项
    genderOptions: [
      {
        value: 'male',
        label: '男孩子',
        icon: 'icon_male.png',
        iconSelected: 'icon_male_choice.png'
      },
      {
        value: 'female',
        label: '女孩子',
        icon: 'icon_female.png',
        iconSelected: 'icon_female_choice.png'
      }
    ],
    
    // 页面状态
    isLoading: false,
    canSave: false,
    showBirthdayPicker: false,
    
    // 原始数据（用于比较是否有修改）
    originalData: {}
  },

  onLoad(options) {
    console.log('编辑宠物页面加载', options);
    
    // 获取系统信息
    this.getSystemInfo();
    
    // 获取宠物ID
    if (options.petId) {
      this.setData({
        petId: options.petId
      });
      // 加载宠物详情
      this.loadPetDetail();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  /**
   * 获取系统信息
   */
  getSystemInfo() {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight || 44
    });
  },

  /**
   * 加载宠物详情
   */
  async loadPetDetail() {
    try {
      wx.showLoading({
        title: '加载中...'
      });

      const result = await apiService.getPetDetail(this.data.petId);
      if (result.success) {
        const pet = result.data;
        const formData = {
          nickname: pet.name || '',
          category: pet.category || (pet.species && pet.species.includes('猫') ? 'cat' : 'dog'),
          breed: pet.species || '',
          gender: pet.gender === '公' ? 'male' : 'female',
          birthDate: pet.birthday ? this.formatDate(new Date(pet.birthday)) : '',
          weight: pet.weight ? pet.weight.toString() : '',
          avatar: pet.avatar || ''
        };

        this.setData({
          formData: formData,
          originalData: JSON.parse(JSON.stringify(formData))
        });

        this.checkCanSave();
      } else {
        wx.showToast({
          title: result.message || '加载失败',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    } catch (error) {
      console.error('加载宠物详情失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 格式化日期
   */
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  /**
   * 返回上一页
   */
  onBack() {
    // 检查是否有修改
    if (this.hasChanges()) {
      wx.showModal({
        title: '提示',
        content: '您有未保存的修改，确定要离开吗？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateBack();
          }
        }
      });
    } else {
      wx.navigateBack();
    }
  },

  /**
   * 检查是否有修改
   */
  hasChanges() {
    const { formData, originalData } = this.data;
    return JSON.stringify(formData) !== JSON.stringify(originalData);
  },

  /**
   * 选择头像
   */
  onChooseAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({
          'formData.avatar': tempFilePath
        });
        this.checkCanSave();
      }
    });
  },

  /**
   * 昵称输入
   */
  onNicknameInput(e) {
    this.setData({
      'formData.nickname': e.detail.value
    });
    this.checkCanSave();
  },

  /**
   * 选择类别
   */
  onCategorySelect(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      'formData.category': category
    });
    this.checkCanSave();
  },

  /**
   * 品种输入
   */
  onBreedInput(e) {
    this.setData({
      'formData.breed': e.detail.value
    });
    this.checkCanSave();
  },

  /**
   * 选择性别
   */
  onGenderSelect(e) {
    const gender = e.currentTarget.dataset.gender;
    this.setData({
      'formData.gender': gender
    });
    this.checkCanSave();
  },

  /**
   * 选择出生日期
   */
  onBirthDateSelect() {
    this.setData({
      showBirthdayPicker: true
    });
  },

  /**
   * 生日选择确认
   */
  onBirthdayConfirm(e) {
    // 兼容两种数据格式：{year, month, day} 或 {date}
    let birthDate;
    if (e.detail.year && e.detail.month && e.detail.day) {
      // 格式化为 YYYY-MM-DD
      const year = e.detail.year;
      const month = String(e.detail.month).padStart(2, '0');
      const day = String(e.detail.day).padStart(2, '0');
      birthDate = `${year}-${month}-${day}`;
    } else if (e.detail.date) {
      birthDate = e.detail.date;
    } else {
      console.error('生日选择器返回的数据格式不正确:', e.detail);
      return;
    }
    
    this.setData({
      'formData.birthDate': birthDate,
      showBirthdayPicker: false
    });
    this.checkCanSave();
  },

  /**
   * 生日选择取消
   */
  onBirthdayCancel() {
    this.setData({
      showBirthdayPicker: false
    });
  },

  /**
   * 体重输入
   */
  onWeightInput(e) {
    this.setData({
      'formData.weight': e.detail.value
    });
    this.checkCanSave();
  },

  /**
   * 检查是否可以保存
   */
  checkCanSave() {
    const { formData } = this.data;
    const canSave = formData.nickname.trim() && 
                   formData.category && 
                   formData.breed.trim() && 
                   formData.gender && 
                   formData.weight.trim() &&
                   this.hasChanges();
    
    this.setData({
      canSave: canSave
    });
  },

  /**
   * 保存修改
   */
  async onSave() {
    if (!this.data.canSave || this.data.isLoading) {
      return;
    }

    // 表单验证
    const validation = this.validateForm();
    if (!validation.valid) {
      wx.showToast({
        title: validation.message,
        icon: 'none'
      });
      return;
    }

    this.setData({
      isLoading: true
    });

    try {
      // 上传头像（如果有新头像）
      let avatarUrl = this.data.formData.avatar;
      if (avatarUrl && avatarUrl.startsWith('http://tmp/')) {
        const uploadResult = await this.uploadAvatar(avatarUrl);
        if (uploadResult.success) {
          avatarUrl = uploadResult.url;
        }
      }

      // 保存到服务器
      const saveResult = await this.updatePetToServer({
        ...this.data.formData,
        avatar: avatarUrl
      });

      if (saveResult.success) {
        // 更新原始数据
        this.setData({
          originalData: JSON.parse(JSON.stringify(this.data.formData))
        });
      }
    } catch (error) {
      console.error('保存失败:', error);
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({
        isLoading: false
      });
    }
  },

  /**
   * 表单验证
   */
  validateForm() {
    const { formData } = this.data;
    
    if (!formData.nickname.trim()) {
      return { valid: false, message: '请输入宠物昵称' };
    }
    
    if (!formData.category) {
      return { valid: false, message: '请选择宠物类别' };
    }
    
    if (!formData.breed.trim()) {
      return { valid: false, message: '请输入宠物品种' };
    }
    
    if (!formData.gender) {
      return { valid: false, message: '请选择宠物性别' };
    }
    
    if (!formData.weight.trim()) {
      return { valid: false, message: '请输入宠物体重' };
    }
    
    const weight = parseFloat(formData.weight);
    if (isNaN(weight) || weight <= 0 || weight > 100) {
      return { valid: false, message: '请输入有效的体重(0-100kg)' };
    }
    
    return { valid: true };
  },

  /**
   * 上传头像
   */
  async uploadAvatar(filePath) {
    try {
      // 这里应该调用真实的上传接口
      // 暂时返回模拟数据
      return {
        success: true,
        url: this.data.formData.category === 'dog' ? '/assets/common/img_dog_avatar_default.png' : '/assets/common/img_cat_avatar_default.png'
      };
    } catch (error) {
      console.error('头像上传失败:', error);
      return {
        success: false,
        message: '头像上传失败'
      };
    }
  },

  /**
   * 更新宠物到服务器
   */
  async updatePetToServer(petData) {
    try {
      // 转换数据格式以匹配API
      const apiData = {
        name: petData.nickname,
        species: petData.breed,
        gender: petData.gender === 'male' ? '公' : '母',
        birthday: petData.birthDate ? new Date(petData.birthDate).getTime() : null,
        weight: parseFloat(petData.weight) || 0,
        avatar: petData.avatar || '',
        category: petData.category
      };

      console.log('更新宠物数据:', apiData);
      const result = await apiService.updatePet(this.data.petId, apiData);
      
      if (result.success) {
        console.log('宠物更新成功:', result.data);
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000
        });
        
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          });
        }, 1500);
        
        return { success: true, data: result.data };
      } else {
        console.error('宠物更新失败:', result.message);
        wx.showToast({
          title: result.message || '修改失败',
          icon: 'none',
          duration: 2000
        });
        return { success: false, message: result.message };
      }
    } catch (error) {
      console.error('更新宠物异常:', error);
      wx.showToast({
        title: '网络异常，请重试',
        icon: 'none',
        duration: 2000
      });
      return { success: false, message: '修改失败，请重试' };
    }
  },

  /**
   * 页面滚动监听
   */
  onPageScroll(e) {
    const scrollY = e.scrollTop;
    
    // 计算导航栏背景透明度，滚动距离0-100px内从透明变为不透明
    const maxScrollDistance = 100; // 滚动距离阈值（像素）
    const opacity = Math.min(scrollY / maxScrollDistance, 1);
    
    // 计算文字颜色，透明度达到0.5时开始变黑
    const textColor = opacity >= 0.5 ? '#120E0C' : '#FFFFFF';
    
    // 只有在透明度或文字颜色发生变化时才更新
    if (this.data.navbarOpacity !== opacity || this.data.navbarTextColor !== textColor) {
      this.setData({
        scrollY: scrollY,
        navbarOpacity: opacity,
        navbarTextColor: textColor
      });
    }
  }
});
